package com.cskaoyan.market.filter;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //告诉浏览器任何来源的主机端口号均可以访问当前服务器
        //表示从哪个主机过来的请求允许访问后端服务器
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:9527");
        //发送请求时，所允许的请求方法
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        //发送请求时允许携带的请求头信息
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type,X-CskaoyanMarket-Admin-Token,X-CskaoyanMarket-Token");
        //是否允许携带cookie的凭证
        response.setHeader("Access-Control-Allow-Credentials","true");

        //该响应的资源是否被允许与给定的origin共享 通常在允许携带cookie时需要设置
        filterChain.doFilter(request,response);
    }
}
